package com.gg.fruit.controller;

import base.BaseServlet;
import com.gg.beanhelper.BeanHelper;
import com.gg.entity.Fruit;
import com.gg.fruit.service.FruitService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/UpdateFruitServlet")
public class UpdateFruitServlet extends BaseServlet {
    @Autowired
    private FruitService fruitService;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int fid=Integer.parseInt(request.getParameter("fid"));
        Fruit fruit=new Fruit();
        fruit.setFid(fid);
        fruit=fruitService.getFruitByFid(fruit);
        request.getSession().setAttribute("updateFruit", fruit);
        response.sendRedirect("/fruits/admin/BSindex6.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Fruit fruit= BeanHelper.getBean(req.getParameterMap(),Fruit.class);
        Fruit updateFruit= (Fruit) req.getSession().getAttribute("updateFruit");
        fruit.setFid(updateFruit.getFid());
        boolean end=fruitService.updateFruit(fruit);
        resp.setContentType("text/html;charset=utf-8");
        if (end) {
            resp.getWriter().print("<script>alert('更新成功！！！');location.href='/fruits/GetAllFruitsServlet?pageNum=1'</script>");
        }else{
            resp.getWriter().print("<script>alert('更新失败！！！');location.href='/fruits/admin/BSindex6.jsp'</script>");
        }
    }
}
